<template>
  <div>
    <el-dialog
      fullscreen
      :title="$t('查看批次')"
      destroy-on-close
      append-to-body
      :visible.sync="show"
      :before-close="cancel"
    >
      <div style="text-align: right; margin-bottom: 10px; line-height: 20px">
        <div>{{ $t('完成数/包裹数') }}</div>
        <div style="font-weight: bold">
          <div>{{ formData.completeNum }}/{{ formData.num }}</div>
        </div>
      </div>
      <div class="view-batch">
        <!-- 行程 -->
        <div class="view-batch-left">
          <template v-if="routeBatchDetailsList.length">
            <div
              :style="{
                background: item.selected ? 'rgba(103, 194, 58, 0.7)' : '',
              }"
              class="view-batch-left_item"
              @click="handleRoute(item)"
              v-for="item in routeBatchDetailsList"
              :key="item.routeId"
            >
              <div>
                {{ item.routeNo }}
              </div>
              <div>{{ item.expectedTime }}h</div>
            </div>
          </template>
          <el-empty v-else :description="$t('暂无路线')" />
        </div>
        <!-- 地图 -->
        <div v-show="detail.routeId" class="view-batch-map" id="batchDispatchMap" ref="mapRef"></div>
        <!-- 详情 -->
        <div class="view-batch-right" v-if="detail.routeId">
          <div class="view-batch-right_detail">
            <el-divider content-position="left">{{ $t('车辆') }}</el-divider>
            <div class="detail-item">{{ detail.vehicleName }}</div>
            <el-divider content-position="left">{{ $t('负责人') }}</el-divider>
            <div style="padding: 0 10px">
              <el-select disabled style="width: 100%" v-model="user" multiple clearable filterable>
                <el-option
                  v-for="item in routeBatchDetailsUserLis"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </div>
            <el-divider content-position="left">{{ $t('包裹数') }}</el-divider>
            <div class="detail-item">{{ detail.packageNum }}个</div>
            <el-divider content-position="left">{{ $t('预计用时') }}</el-divider>
            <div class="detail-item">{{ detail.expectedTime }} h</div>
          </div>
          <div>
            <el-button
              type="primary"
              style="width: 100%"
              v-hasPermi="['distribution:googleRouteBatch:printShipments']"
              @click="handlePrintShipments"
            >
              {{ $t('打印此行程面单') }}
            </el-button>
          </div>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="cancel">{{ $t('关闭') }}</el-button>
      </div>
    </el-dialog>

    <!-- 打印面单 -->
    <Print :show.sync="print.show" :formData="print.formData" @getList="getList" />
    <!-- 包裹详情 -->
    <PackageDetail
      :showDeleteBtn="false"
      :show.sync="packageDetail.show"
      :formData="packageDetail.formData"
      @getList="getList"
    />
  </div>
</template>

<script>
import {
  getRouteBatchDetailsUserList,
  printShipments,
  setRouteUser,
  getRouteBatchDetailsList,
} from '@/api/orderManage/batchDispatch'
import { orderPackageList } from '@/api/distribution/orderBatchs/index'

import { getStartLocation } from '@/api/orderManage/myDispatch'
import Print from './print.vue'
import PackageDetail from './editBatch/packageDetail.vue'
import Marker from './editBatch/marker.vue'
import Vue from 'vue'

export default {
  components: { Print, PackageDetail },

  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: () => ({}),
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      /**包裹详情 */
      packageDetail: { show: false, formData: {} },
      /**
       * @description 起点marker
       * @type {google.maps.marker.AdvancedMarkerElement}
       * */
      startMarker: null,
      /**打印面单 */
      print: {
        show: false,
        formData: {},
      },
      center: { lat: 35.6895, lng: 139.6917 },
      map: null,
      user: null,
      routeBatchDetailsList: [],
      routeBatchDetailsUserLis: [],
      detail: {},
      lineColors: ['#32CCBC', '#F6416C', '#28C76F', '#ff7003', '#9708CC'],
      lineColorsIndex: 0,
      markers: [],
      polylines: [],
    }
  },
  computed: {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.initMap()
        this.detail = {}
        this.getList()
      }
    },
  },
  methods: {
    /**设置起点marker */
    async setStartMarker() {
      const { AdvancedMarkerElement } = await google.maps.importLibrary('marker')
      const img = document.createElement('img')
      img.src = require('@/assets/images/startPoint.png')
      img.className = 'google-start-marker'
      getStartLocation().then((res) => {
        const { latitude, longitude } = res
        const position = { lat: latitude, lng: longitude }
        this.startMarker = new AdvancedMarkerElement({
          map: this.map,
          position,
          content: img,
        })
      })
    },
    handlePrintShipments() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      const data = {
        routeId: this.detail.routeId,
      }
      printShipments(data)
        .then(async (res) => {
          const data = res.data.batchPackage
          data[data.length - 1].isLast = true
          for (let index = 0; index < data.length; index++) {
            data[index].packageNoSrc = await this.createQRCode({
              width: 100,
              height: 100,
              text: data[index].packageNo,
            })
            data[index].packageNoSrc2 = await this.createQRCode({
              width: 83,
              height: 83,
              text: data[index].packageNo,
            })
            data[index].linkSrc = await this.createQRCode({
              width: 100,
              height: 100,
              text: data[index].link,
            })
          }

          this.print.formData = data
          this.print.show = true
        })
        .finally(() => loading.close())
    },
    handleSetRouteUser() {
      const data = {
        routeId: this.detail.routeId,
        userIds: this.user.toString(),
      }
      setRouteUser(data).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.$message({ type: 'success', message: msg })
          const routeId = this.routeBatchDetailsList.find((i) => i.selected).routeId
          this.getList(routeId)
        }
      })
    },
    /**创建组件挂载 */
    createComponent(vueComponents, propsData) {
      // 创建一个临时的 Vue 实例来渲染组件
      const Component = Vue.extend(vueComponents)
      const instance = new Component({
        propsData: { ...propsData },
      })
      instance.$mount()
      return instance
    },
    async addMarker(params) {
      const { position, index, lineColor, polyline, item } = params
      const { AdvancedMarkerElement } = await google.maps.importLibrary('marker')
      /** @type {google.maps.marker.AdvancedMarkerElement}*/
      const marker = await new AdvancedMarkerElement({
        map: this.map,
        position,
        content: this.createComponent(Marker, { lineColor, index, title: index }).$el,
      })
      marker.addListener('click', () => {
        console.log(`item ==>`, item)
        orderPackageList({ packageNo: item.packageNo, routeId: item.routeId }).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.packageDetail.formData = { ...res.rows[0], item }
            this.packageDetail.show = true
          }
        })
      })
      this.polylines.push(polyline)
      this.markers.push(marker)
    },
    /**重复设置颜色 */
    getColor() {
      let color
      if (this.lineColorsIndex < this.lineColors.length - 1) {
        color = this.lineColors[this.lineColorsIndex]
        this.lineColorsIndex += 1
      } else {
        this.lineColorsIndex = 0
        color = this.lineColors[this.lineColorsIndex]
        this.lineColorsIndex += 1
      }
      return color
    },
    handleRoute(item) {
      this.routeBatchDetailsList.forEach((i) => (i.selected = false))
      item.selected = true
      this.detail = {
        ...item,
      }
      this.user = item.userIds?.split(',').map((id) => +id) || []

      // 要清空谷歌地图上的所有线（Polyline）和标记（Marker）
      this.markers.map((m) => m.setMap(null))
      this.markers = []
      this.polylines.map((p) => p.setMap(null))
      this.polylines = []
      this.lineColorsIndex = 0
      if (item.routeList.length == 0) return
      this.drawLines(item.routeList)
    },
    /**设置中心点位 */
    setMapCenter({ lat, lng }) {
      this.map.setCenter({ lat, lng })
    },
    initMap() {
      this.$nextTick(() => {
        this.map = new google.maps.Map(this.$refs['mapRef'], {
          zoom: 10,
          center: this.center,
          mapId: 'setRoute_map',
        })
      })
    },
    /**绘制线路图 */
    async drawLines(data) {
      if (!this.map) return
      const {
        encoding: { decodePath },
      } = await google.maps.importLibrary('geometry')
      let self = this
      /**@type {Array} */
      const pathArr = data.map((i) => {
        return {
          ...i,
          path: decodePath(i.routePolyLine),
        }
      })

      pathArr.map((item, index) => {
        const routePolylineIndex = item.routePolylineIndex

        const strokeColor = this.getColor()
        const polyline = new google.maps.Polyline({
          path: item.path,
          geodesic: true,
          strokeColor,
          strokeOpacity: 1.0,
          strokeWeight: routePolylineIndex % 2 == 0 ? 6 : 5,
          zIndex: routePolylineIndex,
        })
        polyline.setMap(this.map)
        // google.maps.event.addListener(polyline, 'click', function (event) {
        //   console.log(`this ==>`, this)
        // })
        polyline.addListener('mouseover', function () {
          this.setOptions({
            strokeColor: '#000',
            zIndex: pathArr.length,
          })
        })
        polyline.addListener('mouseout', function () {
          this.setOptions({
            strokeColor,
            zIndex: routePolylineIndex,
          })
        })

        // 添加marker
        this.addMarker({
          polyline,
          position: item.path[item.path.length - 1],
          index: item.routePolyLineIndex,
          lineColor: strokeColor,
          item,
        })
      })
      // // 调整地图视图以适应路径
      const bounds = new google.maps.LatLngBounds()
      if (pathArr.length > 0) {
        pathArr[0].path.forEach((point) => bounds.extend(point))
      }
      this.map.fitBounds(bounds)
    },
    getList(routeId) {
      const data = {
        batchId: this.formData.id,
      }
      getRouteBatchDetailsList(data).then((res) => {
        this.setStartMarker()
        // 判断刷新之前是否选择
        if (routeId) {
          this.routeBatchDetailsList.forEach((i) => {
            if (i.routeId == routeId) {
              i.selected = true
              this.detail = { ...i }
            }
          })
        } else {
          this.routeBatchDetailsList = res.data.map((i) => {
            return {
              ...i,
              selected: false,
            }
          })
        }
      })

      //
      getRouteBatchDetailsUserList(data).then((res) => {
        console.log(`res ==>`, JSON.parse(JSON.stringify(res)))
        this.routeBatchDetailsUserLis = res.data
      })
    },

    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style scoped lang="scss">
.view-batch {
  display: flex;
  height: 75vh;
  $border: 1px solid #ccc;
  &-left {
    width: 300px;
    border: $border;
    //border-right: 0;
    overflow: auto;
    &::-webkit-scrollbar {
      width: 0;
    }
    &_item {
      padding: 15px;
      border-bottom: $border;
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      &:hover {
        background: rgba(103, 194, 58, 0.3);
      }
    }
  }
  &-map {
    flex: 1;
    border: $border;
  }
  &-right {
    width: 300px;
    border: $border;
    border-left: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    &_detail {
      .detail-item {
        padding: 10px 40px;
      }
    }
  }
}
</style>
